package util;

import com.google.gson.Gson;
import entity.BaseModel;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.resource.FileResourceLoader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class ConfigUtil {
    protected static final GroupTemplate gt;
    protected static final BaseModel bm;

    static {
        String root = String.format("%s%s%s%s%s%s%s%s%s", System.getProperty("user.dir"), File.separator, "src", File.separator, "main", File.separator, "resources", File.separator, "beetle");
        FileResourceLoader resourceLoader = new FileResourceLoader(root, "utf-8");
        Configuration cfg = null;
        try {
            cfg = Configuration.defaultConfiguration();
        } catch (IOException e) {
            e.printStackTrace();
        }
        gt = new GroupTemplate(resourceLoader, cfg);
//        gt.setSharedVars((Map) properties);

        String config = String.format("%s%s%s%s%s%s%s%s%s", System.getProperty("user.dir"), File.separator, "src", File.separator, "main", File.separator, "resources", File.separator, "config1.json");
        config = readFileByLines(config);
        bm = new Gson().fromJson(config, BaseModel.class);
    }

    /**
     * 以行为单位读取文件，常用于读面向行的格式化文件
     */
    public static String readFileByLines(String fileName) {
        File file = new File(fileName);
        BufferedReader reader = null;
        String rs = "", tempString;
        try {
            System.out.println(ConfigUtil.class.getName() + "已读取配置文件=======================>>>" + fileName);
            reader = new BufferedReader(new FileReader(file));
            int line = 1;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                // 显示行号
//                if (tempString.contains("//")) continue;
//                System.out.println(tempString);
                rs += tempString;
                line++;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return rs;
    }

}
